from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
import datetime

from django.utils import simplejson

from project import ProjectHandler
from testing import TestingHandler
from google.appengine.api import urlfetch


from ft_utils import *
from record import *
from upload import UploadHandler

from google.appengine.api import memcache
from iform import IformHandler

from download import DownloadHandler
from apptest import ApptestHandler
from report import ReportHandler
from manage import ManageHandler
from google.appengine.api import users
from google.appengine.ext.webapp import template

import os



    


class MainHandler(webapp.RequestHandler):
    def get(self):
        if users.get_current_user():
             values = {
              'user': users.GetCurrentUser(),
              'admin_url': '/manage',
              'logout_url': users.CreateLogoutURL('http://' + self.request.host + '/')
            }

             path = os.path.join(os.path.dirname(__file__), 'template/workspace.html')
             self.response.out.write(template.render(path, values))




             

        
        

     
class ProjectHandler2(webapp.RequestHandler):
    def get(self):
        pass
    def post(self):
        '''
        Backend for a tree
        Root(hidden)
        -2011                        (id:year--2011)
        -2010
            - Project A              (id:project--2011-project_a)
            - Project B
                - Compaction         (id:testing--project_b--432115)
                    - 2010-01-10     (id:form--423271--4 //form-testing_tableid--parent_record_id)
                    - 2010-02-10
                - Asphalt
                    - 2010-01-10
                    - 2010-02-10
        '''
        MAPPING = getMapping()
        PROJECT_TABLE = 423203
        node = self.request.get('node')
        results = []
        NO_YEAR = 3
        this_year = datetime.now().year
        ft_client = getFtClient(USERNAME, PASSWORD)
        if node=='root':
            #load the intial tables
            #-2011
            #-2010
            #-2009
            #-Older
            #-All Tables
            for y in range(this_year, this_year-NO_YEAR, -1):
                results.append({'text': y, 'id': 'year--%s' % y, 'cls': 'folder'})
            results.append({'text': 'Older' , 'id': 'older', 'cls': 'folder'})
            results.append({'text': 'All Tables' , 'id': 'tables', 'cls': 'folder'})
        elif node=='tables':
            #Open the all tables folder
            response = processResponse(ft_client.query(SQL().showTables()))
            for t in response:
                results.append({'text': t['name'] , 'id': t['table id'], 'cls': 'file', 'leaf': True})
        elif node=='older':
            #open the older folder
            #select everything older than this_year-NO_YEAR
            the_year = this_year - NO_YEAR
            response = processResponse(ft_client.query('select project_name, COUNT() as count from %s where date_<=%s GROUP BY project_name' % (PROJECT_TABLE, the_year)))
            for r in response:
                results.append({'text': '%(project_name)s(%(count)s)' % r , 'id':'project--%s--%s' % ('older', r['project_name']), 'cls': 'folder', 'leaf': False})
        elif node.startswith('project'):
            #Open the project folder
            project, year, project_name = node.split('--')
            for testing in MAPPING:
                results.append({'text': styleText(testing['testing_type']) , 'id':'testing--%s--%s--%s' % (year, project_name, testing['project_table_id']), 'cls': 'file', 'leaf': False})
        elif node.startswith('testing'):
            #Open the Testing table
            #form--testing_table_id--parent_record_id
            testing, year, project_name, project_tableid = node.split('--')
            if year=='older':
                sql = "select * from %s where project_name = '%s' and date_<=%s ORDER BY date_" % (project_tableid, project_name, this_year - NO_YEAR)
            else:
                sql = "select * from %s where project_name = '%s' and date_>=%s and date_<%s ORDER BY date_" % (project_tableid, project_name, int(year), int(year)+1)
            response = processResponse(ft_client.query(sql))
            def getTestingTableId():
                for testing in MAPPING:
                    if testing['project_table_id']==project_tableid:
                        return testing['testing_table_id']
            tableid = getTestingTableId()
            for r in response:
                results.append({'text': r['date_'] % r , 'id':'form--%s--%s' % (tableid, r['ID']), 'cls': 'folder', 'leaf': True})
            
        elif node.startswith('year'):
            #everything within a year
            the_year = int(node.split('--')[1])
            rs = {}
            for testing in MAPPING:              
                response = processResponse(ft_client.query('select project_name, COUNT() as count from %s where date_>=%s and date_<%s GROUP BY project_name' % (testing['project_table_id'], the_year, the_year+1)))
                for project in response:
                    ct = rs.setdefault(project['project_name'], 0)
                    rs[project['project_name']] += int(project['count'])
            results = []   
            for project_name, ct in rs.items():
                results.append({'text': styleText('%s(%s)' % (project_name, ct))  , 'id':'project--%s--%s' % (the_year, project_name), 'cls': 'file', 'leaf': False})
            
            
        self.response.out.write(simplejson.dumps(results))


def main():
    application = webapp.WSGIApplication([('/', MainHandler),
                                          ('/projects', ProjectHandler),
                                          ('/report', ReportHandler),
                                          ('/testings', TestingHandler),
                                          ('/iform', IformHandler),
                                          ('/upload', UploadHandler),
                                          ('/apptest', ApptestHandler),
                                          ('/manage', ManageHandler),
                                          ('/download', DownloadHandler)],
                                         debug=True)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
